package org.mentalsmash.tazio.evaluation;

import java.util.Random;

import org.mentalsmash.tazio.evaluation.mock.Counter;
import org.mentalsmash.tazio.impl.WRMTazioStarter;
import org.mentalsmash.tazio.transactions.RollbackException;
import org.mentalsmash.tazio.transactions.Share;
import org.mentalsmash.tazio.transactions.Transaction;
import org.mentalsmash.tazio.transactions.TransactionalSystemException;
import org.mentalsmash.tazio.transactions.UserTransactionManager;
import org.mentalsmash.tazio.transactions.management.TransactionStateException;

public class WRMTest1 {
    public static final int ITERATIONS = 500;

    public static final int MAX_COUNTER = 60;

    public static final String properties = "name:test-counter";

    public static void main(String[] args) {
	String conf = args[0];
	

	WRMTazioStarter starter = new WRMTazioStarter(false, conf);

	starter.initTazio();

	Share share = starter.getShare();
	UserTransactionManager txManager = starter.getTransactionManager();

	Counter testcounter = share.getObject(properties);

	if (testcounter == null) {
	    try {
		testcounter = share.createObject(Counter.class, properties);
	    } catch (TransactionStateException e1) {
		e1.printStackTrace();
		throw new RuntimeException("Cannot retrieve counter object!");
	    } catch (RollbackException e1) {
		e1.printStackTrace();
		throw new RuntimeException("Cannot retrieve counter object!");
	    }
	} else {
	    System.out.println("Object retrieved from the share");
	}

	Transaction tx = null;

	try {
	    Thread.sleep(1000);
	} catch (InterruptedException e1) {
	    // TODO Auto-generated catch block
	    e1.printStackTrace();
	}
	for (int i = 0; i < ITERATIONS; i++) {
	    try {
		tx = txManager.begin();
		int currentVal = testcounter.getValue();
		if (currentVal < MAX_COUNTER) {
		    testcounter.setValue(currentVal + 1);
		    tx.commit();
		    System.out.println("Counter set to " + (currentVal + 1));
		    try {
			Thread.sleep(new Random().nextInt(1000));
		    } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		} else {
		    System.out.println("Counter to its max value");
		    tx.commit();
		    break;
		}
	    } catch (RollbackException e) {
		System.err.println(e.getLocalizedMessage());
	    } catch (TransactionStateException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    } catch (TransactionalSystemException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }

	}

//	JMXDataRetriever retriever = new JMXDataRetriever(host, testId);
//	try {
//	    retriever.dump();
//	} catch (Exception e) {
//	    e.printStackTrace();
//	}
	
//	System.exit(0);

    }
}
